from sqlalchemy import Column, Integer, String, SmallInteger
from werkzeug.security import generate_password_hash, check_password_hash

from apps.libs.error_code import NotFound, AuthFailed
from apps.models.base import Base, db


class User(Base):
    id = Column(Integer, primary_key=True)
    email = Column(String(24), unique=True, nullable=False)
    nickname = Column(String(24), unique=True)
    auth = Column(SmallInteger, default=1)
    _password = Column('password', String(100))

    # 指明需要序列化的属性
    def keys(self):
        return ['id', 'email', 'auth', 'nickname']

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, pwd):
        self._password = generate_password_hash(pwd)

    @staticmethod
    def register_by_email(nickname, acount, secret):
        with db.auto_commit():
            user = User()
            user.nickname = nickname
            user.email = acount
            user.password = secret
            db.session.add(user)

    @staticmethod
    def verify(email, password):
        user = User.query.filter_by(email=email).first()
        if not user:
            raise NotFound(msg='为找到该用户！')
        if not user.check_password(password):
            raise AuthFailed()
        # 判断当前用户是否是管理员
        if user.auth == 2:
            scope = 'AdminScope'
        elif user.auth == 3:
            scope = 'SuperScope'
        else:
            scope = 'UserScope'

        return {'uid':user.id, 'scope':scope}

    def check_password(self, raw):
        if not self._password:
            return False
        return check_password_hash(self._password, raw)






